import Taro from '@tarojs/taro';
import wxRequest2Curl from './wxRequest2Curl';
import logout from './logout';

function parseJSON(response: any) {
  return JSON.parse(response.data);
}

function checkStatus(response: any) {
  if (response.statusCode >= 200 && response.statusCode < 300) {
    return response;
  }
  if (response.statusCode === 401) {
    logout()
  }
  const error: any = new Error(response);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default async function request(url: string, options?: any) {
  if (options.headers) {
    options.header = options.headers;
    delete options.headers;
  }
  console.log(wxRequest2Curl({ ...options, url }));
  return Taro.request({ timeout: 10 * 1000, ...options, url, })
    .then(checkStatus)
    .then(response => response.data)
    .then((data: any) => ({ data, success: true }))
    .catch((err: any) => {
      console.log('err', JSON.stringify(err))
      return { err, success: false };
    });
}

export async function uploadRequst(url: string, options?: any) {
  const { filePath, name, headers, formData } = options;
  console.log('uploadRequst', formData, filePath,name)
  return Taro.uploadFile({
    url,
    filePath: filePath,
    formData,
    timeout: 120 * 1000,
    name,
    header: headers,
  }).then(checkStatus)
    .then(parseJSON)
    .then(data => ({ data, success: true }))
    .catch(err => ({ err, success: false }))
}
